package com.hoopchina.ui.details;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Toast;
import com.hoopchina.news.R;
import com.hoopchina.meta.NewsItem;
import com.hoopchina.ui.home.HomeView;
import com.hoopchina.ui.main.BaseActivity;
import com.hoopchina.ui.main.INewsListViewObserver;
import com.hoopchina.ui.main.NewsListItemView;
import com.hoopchina.ui.main.NewsListView;
import com.hoopchina.ui.main.ViewManager;
import com.hoopchina.util.LogUtils;
import com.hoopchina.util.NetUtil;
import com.hoopchina.util.xml.NewsItemXML;
import com.hoopchina.weibo.ui.BindingDBEngine;
import com.hoopchina.weibo.ui.ForwardingView;
import com.hoopchina.weibo.ui.WeiboAuthActivity;

/**
 * 百度新闻我的收藏界面
 * 
 * @author Neusoft
 *
 */
public class MyFavoritesView extends BaseActivity implements INewsListViewObserver {
    public static final String            Id = "MyFavoritesView";
    /** Called when the activity is first created. */  
    private NewsListView           mListView;
    private List<NewsItem>         mNewsList;
    private List<NewsItem>         mMoreList;
	private int mCurrentPosition;
	private FavoritesEngine OperationDB;
	private int mConfirmDialogId = 1;
	private int mFavoritesNewsCount;
	private int mNewsCountShows;
	private int mMoreNewsCount;
	private Cursor cur;

    @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.myfavoriteslist);
		mMyHandleBackButton = true;
		mViewManager.setTitleBarVisibility(true);
		mListView = (NewsListView) findViewById(R.id.listviewMyFavoNewsListView);
		mListView.setObserver(this);
		mListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
					@Override
					public void onCreateContextMenu(ContextMenu menu, View v,
							ContextMenuInfo menuInfo) {
						// take user operation trace
						AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
						menu.setHeaderTitle(getString(R.string.popupmenu_headertitle));
						menu.add(0, 0, 0,
								getString(R.string.popupmenu_menu_read));
						menu.add(0, 1, 0,
								getString(R.string.popupmenu_menu_forward));
						menu.add(0, 2, 0,
								getString(R.string.popupmenu_menu_remove));
					}
				});

		mNewsList = new ArrayList<NewsItem>();
		NewsItem mNewsItem;

		OperationDB = new FavoritesEngine(this);
		cur = OperationDB.queryAll();
		mFavoritesNewsCount = cur.getCount();
		if (mFavoritesNewsCount >= 20) {
			mNewsCountShows = 20;
		} else {
			mNewsCountShows = mFavoritesNewsCount;
		}

		if (cur != null) {
			for (int i = 0; i < mNewsCountShows; i++) {
				//cur.moveToNext();
				cur.moveToPosition(i);
				mNewsItem = new NewsItem();
				mNewsItem.setAbs(cur.getString(cur.getColumnIndex("abs")));
				mNewsItem.setAuthor(cur.getString(cur.getColumnIndex("author")));
				mNewsItem.setImgUrl(cur.getString(cur.getColumnIndex("imgurl")));
				mNewsItem.setTime(cur.getString(cur.getColumnIndex("time")));
				mNewsItem.setTitle(cur.getString(cur.getColumnIndex("title")));
				mNewsItem.setUrl(cur.getString(cur.getColumnIndex("url")));
				
				mNewsList.add(mNewsItem);
			}
			cur.close();
		}
		// OperationDB.closeDatabase();

		mListView.setDataList(mNewsList , false);
	}
    
    @Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			Bundle bundle = new Bundle();
			bundle.putInt("Type", 1);
			bundle.putString("title", mNewsList.get(mCurrentPosition)
					.getTitle());
			bundle.putString("ImageUrl", mNewsList.get(mCurrentPosition)
					.getImgUrl());
			bundle.putString("Url", mNewsList.get(mCurrentPosition).getUrl());
			bundle.putString("Author", mNewsList.get(mCurrentPosition)
					.getAuthor());
			bundle.putString("time", mNewsList.get(mCurrentPosition).getTime());
			bundle.putString("Abs", mNewsList.get(mCurrentPosition).getAbs());

			mViewManager.setTabBarVisibility(false);
			mViewManager.showClearOnTopView(DetailsView.Id, DetailsView.class,
					true, bundle);
			break;
		case 1:
			final CharSequence[] items = {
          		  getResources().getString(R.string.forward_select_item_sina)
          		, getResources().getString(R.string.forward_select_item_tencent)
          		, getResources().getString(R.string.forward_select_item_sohu)
          		, getResources().getString(R.string.forward_select_item_netease)
          		, getResources().getString(R.string.forward_select_item_renren)}; 
            AlertDialog.Builder builder = new AlertDialog.Builder(MyFavoritesView.this);
            builder.setTitle(getResources().getString(R.string.forward_select_dialog_title));
            builder.setItems(items, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
	        		if (!NetUtil.checkNet(MyFavoritesView.this)) {
	        			Toast.makeText(mViewManager.getCurrentActivity(),
	        					getResources().getString(R.string.app_no_network),
	        					Toast.LENGTH_SHORT).show();
	        		}
	        		else
	        		{
	                    Bundle aBundle = new Bundle();
	                    aBundle.putInt("WeiboType", item);
	                    aBundle.putString("Title", mNewsList.get(mCurrentPosition+1).getTitle());
	                    aBundle.putString("ImageUrl", mNewsList.get(mCurrentPosition+1).getImgUrl());
	                    aBundle.putString("NewsUrl", mNewsList.get(mCurrentPosition+1).getUrl());
	                    aBundle.putString("Abstract", mNewsList.get(mCurrentPosition+1).getAbs());
	                    aBundle.putString("Author", mNewsList.get(mCurrentPosition+1).getAuthor());
	                    aBundle.putBoolean("FromBindingPage", false);
	 	           		BindingDBEngine mEngine = new BindingDBEngine(MyFavoritesView.this);
	 	         		if ( mEngine.isBinding( item ) ) {
	 	         			ForwardingView.setOldView(MyFavoritesView.Id, MyFavoritesView.class);
	 	                     ViewManager.getInstance().showClearOnTopView( ForwardingView.Id,
	 	                     		ForwardingView.class, false, aBundle);
	 	         		} else {
	 	         			WeiboAuthActivity.setOldView(MyFavoritesView.Id, MyFavoritesView.class);
	 	                     ViewManager.getInstance().showClearOnTopView(WeiboAuthActivity.Id,
	 	                    		 WeiboAuthActivity.class, false, aBundle);
	 	         		}
	        		}

                }
            });
            builder.create().show();
			break;			
		case 2:
			// Toast.makeText(this, "取消收藏", 2000).show();
			// mLinearLayout = (LinearLayout)
			// this.findViewById(R.id.myfavoriteslistview);
			// mLinearLayout.removeAllViews();
			showDialog(mConfirmDialogId);

			break;
		default:
			break;
		}

		return super.onContextItemSelected(item);
	}   
    
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			goBack();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	public void goBack() {
		Bundle intent = getIntent().getExtras();

		if (intent == null) {

			ViewManager.getInstance().showView(DetailsView.Id,
					DetailsView.class, false, null);
			Log.i("goback","log content3");
			return;
		}

		String LaunchType = intent.getString("LaunchType");
		if (LaunchType.equalsIgnoreCase("FromDetailMenu")) {
			ViewManager.getInstance().showView(DetailsView.Id,
					DetailsView.class, false, null);
			Log.i("goback","log content1");
		} else if (LaunchType.equalsIgnoreCase("FromHomeListMenu")) {
			ViewManager.getInstance().showView(HomeView.Id,
					HomeView.class, false, null);
			Log.i("goback","log content2");
		}else{
			ViewManager.getInstance().showView(DetailsView.Id,
					DetailsView.class, false, null);
			Log.i("goback","log content3");
		}
	}
    
    @Override
	public void onResume() {
		super.onResume();

		mViewManager.hideLeftButton();
		mViewManager.setTitle(getString(R.string.favorates_Title));
		mViewManager.setStatus("");
		mListView.displayLoadMoreButton(false);
   
		mViewManager.setAssistButton("", R.drawable.titlebar_btn_assist_selector,
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						mViewManager.showView(HomeView.Id, HomeView.class,
								false, null, true);
						// Toast.makeText(mViewManager.getCurrentActivity(),
						// "刷新", Toast.LENGTH_SHORT ).show();
					}
				});

	}
    
	/*
	 * 创建取消收藏二次确认对话框
	 * @param id 对话框的id
	 */
    @Override 
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		super.onCreateDialog(mConfirmDialogId);
		AlertDialog.Builder builder = new AlertDialog.Builder(MyFavoritesView.this);
		// builder.setIcon(android.R.drawable.alert_dark_frame);//图标
		builder.setTitle(getString(R.string.alertDialog_title));
		builder.setPositiveButton(getString(R.string.alertDialog_confirm),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						OperationDB.delete(mNewsList.get(mCurrentPosition)
								.getTitle());
						mNewsList.remove(mCurrentPosition);
						mListView.setDataList(mNewsList,false);
						mListView.notifyDataSetChanged();
						mListView.displayLoadMoreButton(false);
					}
				});
		builder.setNegativeButton(getString(R.string.alertDialog_cancel),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
		return builder.create();
	}   
    
    
  @Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return false;
	}

	@Override
	public void onNewsListItemClick(AdapterView<?> parent, View view,
			int position, long id) {
		Bundle bundle = new Bundle();
		bundle.putInt("Type", 1);
		bundle.putString("title", mNewsList.get(position).getTitle());
		bundle.putString("ImageUrl", mNewsList.get(position).getImgUrl());
		bundle.putString("Url", mNewsList.get(position).getUrl());
		bundle.putString("Author", mNewsList.get(position).getAuthor());
		bundle.putString("time", mNewsList.get(position).getTime());
		bundle.putString("Abs", mNewsList.get(position).getAbs());

		mViewManager.setTabBarVisibility(false);
		mViewManager.showClearOnTopView(DetailsView.Id, DetailsView.class,
				true, bundle);
	}

	@Override
	public void onNewsListItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		mCurrentPosition = position;
	}

	@Override
	public void onNewsListHeaderClick(AdapterView<?> parent, View view,
			int position, long id) {

	}

	@Override
	public void onClickLoadMoreButton() {
		mListView.setLoadMoreButtonEnable(false);
		mListView.setLoadMoreButtonText(R.string.remind_loading_baidu_news);
		mListView.setLoadMoreProgressBarVisibility(View.VISIBLE);
		getMoreList();
		mListView.setLoadMoreButtonText(R.string.app_list_view_load_more_button);
		mListView.setLoadMoreProgressBarVisibility(View.INVISIBLE);				
		mListView.notifyDataSetChanged();
		mListView.setLoadMoreButtonEnable(true);
	}
	
	/*
	 * 加载更多，加载条数由上边常量参数设定
	 */
	private void getMoreList(){
//		List<NewsItem> list = addNext20Item();
//		mNewsList.addAll(list);
		cur = OperationDB.queryAll();
		mFavoritesNewsCount = cur.getCount();		

		NewsItem mNewsItem;
		
		//当前的Cur位置等于已经显示的新闻数目
		int mCurrentCurPosition = mNewsList.size();
		cur.moveToPosition(mCurrentCurPosition);
		
		//没有显示的收藏新闻数目
		int mRemainderNewsCount = mFavoritesNewsCount - mCurrentCurPosition;
		
		if ( mRemainderNewsCount >= 2 ){
			mMoreNewsCount = 2;
		}else
		{
			mMoreNewsCount = mRemainderNewsCount;
		}
		
		if (cur != null && mMoreNewsCount != 0) {
			for (int i = mCurrentCurPosition; i < mCurrentCurPosition + mMoreNewsCount ; i++) {
				//cur.moveToNext();
				cur.moveToPosition(i);
				mNewsItem = new NewsItem();
				mNewsItem.setAbs(cur.getString(cur.getColumnIndex("abs")));
				mNewsItem.setAuthor(cur.getString(cur.getColumnIndex("author")));
				mNewsItem.setImgUrl(cur.getString(cur.getColumnIndex("imgurl")));
				mNewsItem.setTime(cur.getString(cur.getColumnIndex("time")));
				mNewsItem.setTitle(cur.getString(cur.getColumnIndex("title")));
				mNewsItem.setUrl(cur.getString(cur.getColumnIndex("url")));

				mNewsList.add(mNewsItem);
			}
			cur.close();
		}else{
			return;
		}
		
		mNewsList.size();
		mListView.setDataList(mNewsList , false);
		mListView.notifyDataSetChanged();
	}
	
	/*
	 * 获取下20条收藏项
	 */
	private List<NewsItem> addNext20Item() {
		cur = OperationDB.queryAll();
		mFavoritesNewsCount = cur.getCount();		

		NewsItem mNewsItem;
		
		//当前的Cur位置等于已经显示的新闻数目
		int mCurrentCurPosition = mNewsList.size();
		cur.moveToPosition(mCurrentCurPosition-1);
		
		//没有显示的收藏新闻数目
		int mRemainderNewsCount = mFavoritesNewsCount - mCurrentCurPosition;
		
		if ( mRemainderNewsCount >= 2 ){
			mMoreNewsCount = 2;
		}else
		{
			mMoreNewsCount = mRemainderNewsCount;
		}
		
		if (cur != null) {
			for (int i = 0; i < mMoreNewsCount ; i++) {
				cur.moveToNext();
				mNewsItem = new NewsItem();
				mNewsItem.setAbs(cur.getString(cur.getColumnIndex("abs")));
				mNewsItem.setAuthor(cur.getString(cur.getColumnIndex("author")));
				mNewsItem.setImgUrl(cur.getString(cur.getColumnIndex("imgurl")));
				mNewsItem.setTime(cur.getString(cur.getColumnIndex("time")));
				mNewsItem.setTitle(cur.getString(cur.getColumnIndex("title")));
				mNewsItem.setUrl(cur.getString(cur.getColumnIndex("url")));

				mMoreList.add(mNewsItem);
			}
			cur.close();
		}
		
		
		return mMoreList;
	}
	

	private void goToDetailsView(String title) {
		mViewManager.setTabBarVisibility(false);

		Bundle bundle = new Bundle();
		bundle.putString("newsid", title);
		mViewManager.showClearOnTopView(DetailsView.Id, DetailsView.class,
				true, null);
	}

	@Override
	public void autoLoadMoreList() {	
		getMoreList();
	}
    
}
